import unittest
from pyurl import File, URL
from pyurl.connection import Connection


class BasicFileTests(unittest.TestCase):
    def test_creation(self):
        self.assertEqual(str(File("test")), str(File(URL("test"))))
        
class BaseConnectionTests(unittest.TestCase):
    pass

class ReadConnectionTests(BaseConnectionTests):
    def test_read_file(self):
        file = File(self.test_root, "test_read_file")
        data = file.open("r").read()
        self.assertEqual(data, "This is the content of the test_read_file file")
    
    def test_content_property(self):
        file = File(self.test_root, "test_read_file")
        self.assertEqual(file.content, "This is the content of the test_read_file file")
    
    def test_empty_content_property(self):
        file = File(self.test_root, "test_empty_content_property")
        self.assertEqual(file.content, None)
    
    def test_read_nonexistent_file(self):
        file = File(self.test_root, "test_read_nonexistent_file")
        self.assertRaises(IOError, file.open, "r")
        
    def test_exists_file(self):
        file = File(self.test_root, "test_exists_file")
        self.assertTrue(file.exists)
        file = File(self.test_root, "test_exists_file_does_not_exist")
        self.assertFalse(file.exists)
        
class WriteConnectionTests(BaseConnectionTests):
    def test_write_file(self):
        file = File(self.test_root, "test_write_file")
        stream = file.open("w")
        stream.write("This is the content of the test_write_file file")
        stream.close()
        
        data = file.open("r").read()
        self.assertEqual(data, "This is the content of the test_write_file file")

    def test_content_property(self):
        file = File(self.test_root, "test_write_file_via_content")
        file.content = "This is the content of the test_write_file file"
        
        data = file.open("r").read()
        self.assertEqual(data, "This is the content of the test_write_file file")

    def test_append_file(self):
        file = File(self.test_root, "test_append_file")
        stream = file.open("w")
        stream.write("This is the content of the test_append_file file")
        stream.close()
        
        stream = file.open("a")
        stream.write("\nThis line is appended")
        stream.close()
        
        data = file.open("r").read()
        self.assertEqual(data, "This is the content of the test_append_file file\nThis line is appended")
